package com.zszedu.web.config;

import com.zszedu.web.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;//拦截器

    //添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //拦截的请求
        String[] pathPatterns = {"authentication/{name}/{card}/{phone}/{code}"};//暂时先只拦截注册页面请求，其它请求都不需要拦截

        //不拦截的请求
        String[] excludePathPatterns = {};
        registry.addInterceptor(loginInterceptor). //拦截器类(实现了HandlerInterceptor接口就是拦截器)
                addPathPatterns(pathPatterns). //拦截的请求
                excludePathPatterns(excludePathPatterns); //不拦截的请求
    }

    /***
     * https://zhuanlan.zhihu.com/p/358549471
     * // 拦截所有的请求
     * addMapping("/**")
     *
     * // 可跨域的域名，可以为 *
     * .allowedOriginPatterns("*")
     *
     *  // 允许跨域的方法，可以单独配置
     * allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
     *
     * //该字段可选。它的值是一个布尔值，表示是否允许浏览器发送Cookie. true:支持发送cookie
     * allowCredentials(true)
     *
     * //该字段可选，用来指定本次预检请求的有效期，单位为秒。在有效期间，不用发出另一条预检请求
     * maxAge(3600)
     *
     * // 允许跨域的请求头，可以单独配置
     * allowedHeaders("*");
     */
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}
